package sep.test;

import static com.googlecode.javacv.cpp.opencv_core.cvCloneImage;
import static com.googlecode.javacv.cpp.opencv_core.cvReleaseImage;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.googlecode.javacv.FrameRecorder;
import com.googlecode.javacv.FrameRecorder.Exception;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class IdaImageWriterThread extends Thread {

	private volatile boolean quit = false;

	private final FrameRecorder recorder;
	private final BlockingQueue<IplImage> queue = new LinkedBlockingQueue<IplImage>();

	public IdaImageWriterThread(final FrameRecorder recorder) {
		if (recorder == null)
			throw new IllegalArgumentException("Recorder must not be null.");

		this.recorder = recorder;
	}

	@Override
	public void run() {
		IplImage image = null;

		while (!quit) {
			if (!queue.isEmpty()) {
				image = queue.poll();

				try {
					recorder.record(image);
				} catch (Exception e) {
					System.out.println(e.getMessage());
					quit = true;
				}

				cvReleaseImage(image);
				image = null;
			} else {
				// Prozessorlast reduzieren
				try {
					sleep(1);
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
				}
			}
		}

		// Recorder schliessen
		try {
			recorder.stop();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public void startRecord() {

	}

	public void stopRecord() {
		quit();
	}

	public void quit() {
		quit = true;
	}

	public boolean addImage(IplImage image) {
		return queue.offer(cvCloneImage(image));
	}
}
